//
//  ChatListViewController.m
//  leo
//
//  Created by 常艳 on 15/10/3.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "ChatListViewController.h"
#import "User.h"
#import "Manager.h"
#import "DataManager.h"
#import "LeoMsg.h"
#import "ChatViewController.h"
#import "DropDownViewController.h"
#import "BackgroundViewController.h"
#import "AppDelegate.h"

@interface ChatListViewController ()
@property(nonatomic,strong) NSArray *managers;
@property(nonatomic,strong) SyncManager *syncManager;
@property(nonatomic,strong) DataManager *dataManager;
@property(nonatomic,strong) Watch *selectWatch;
@property(nonatomic,assign) int groupId;
@property(nonatomic,strong) User *user;
@property(nonatomic,assign) BOOL isRegis;
@property(nonatomic,strong) NSString *documentDirectory;
@property(nonatomic,strong) NSArray *watchList;
@property(nonatomic,weak) AppDelegate *mydelegate;
@property(nonatomic,assign) float rate;
@end

@implementation ChatListViewController
-(void)dealloc
{
    [self removeObservers];
    self.managers=NULL;
    self.syncManager=NULL;
    self.dataManager=NULL;
    self.selectWatch=NULL;
    self.documentDirectory=NULL;
    self.watchList=NULL;
    self.mydelegate=NULL;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        UITabBarItem *item = [[UITabBarItem alloc]initWithTitle:@"聊天" image:[UIImage imageNamed:@"tb_msg_icon_normal@2x"] tag:2];
        [item setSelectedImage:[UIImage imageNamed:@"tb_msg_icon_hl@2x"]];
        self.tabBarItem = item;
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.extendedLayoutIncludesOpaqueBars=YES;
    self.navigationController.navigationBar.translucent=NO;
    self.rate=[UIScreen mainScreen].bounds.size.width/375;
    self.isRegis=NO;
    self.isSyncFinish=YES;
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.documentDirectory=[Tooler getDocumentDirectory];
    
    self.dataManager=[[DataManager alloc] init];
    if(self.dataManager==NULL)
    {
        NSLog(@"%@,viewDidLoad,dataManager is null.",chatList_tag);
        [LeoMsg showMsg:@"程序发生错误，code is 8"];
        return;
    }
    self.user=[User sharedSingleton];
    if(self.user==NULL||self.user.uid==NULL)
    {
        NSLog(@"%@,viewDidLoad,user is null.",chatList_tag);
        [LeoMsg showMsg:@"程序发生错误，code is 9"];
        return;
    }

    self.syncManager=[[SyncManager alloc] init];
    if(self.syncManager==NULL)
    {
        NSLog(@"%@,viewDidLoad,syncManager is null.",chatList_tag);
        [LeoMsg showMsg:@"程序发生错误，code is 10"];
        return;
    }
    self.mydelegate=[[UIApplication sharedApplication] delegate];
    if(self.mydelegate==NULL)
    {
        NSLog(@"%@,viewDidLoad,mydelegate is null.",chatList_tag);
        [LeoMsg showMsg:@"程序发生错误，code is 11"];
        return;
    }
    [self loadData];
    [self registerObservers];
 
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    /*
    if(!self.mydelegate.chat_sync)
    {
        [self syncChatData];
        self.mydelegate.chat_sync=YES;
    }
    else
    {*/
    self.user=[User sharedSingleton];
    if(self.user==NULL||self.user.uid==NULL)
    {
        NSLog(@"%@,viewDidLoad,user is null.",chatList_tag);
        [LeoMsg showMsg:@"程序发生错误，code is 9"];
        return;
    }
    if(self.isSyncFinish==YES)
    {
        self.isSyncFinish=NO;
      if(self.mydelegate.chat_sync==NO)
      {
          dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
          if(queue==NULL)
          {
              NSLog(@"%@,getManagerPhotos,queue is null",DATAMANAGER_TAG);
              return;
          }
          dispatch_async(queue, ^{
              [self syncChatData];
          });
        
      }
        
    }
        [self loadData];
        [self.tableView reloadData];
    
        if(self.dataManager==NULL)
            return;
        [self updateUnreadNums];
    //}
    
   
}
-(void)loadData
{
    //取得当前选中的手表
    self.selectWatch=[self.dataManager getActiveWatch:self.user.uid];
    //获取当前家庭圈号
    self.groupId=[self.dataManager getWatchGroupid:self.selectWatch.deviceUid accountId:self.user.uid];
    if(!(self.groupId>0))
    {
        NSLog(@"%@,viewDidLoad,groupId is illegal.",chatList_tag);
        return;
    }
    self.watchList=[self.dataManager getGroupWatchList:self.groupId];
    if(self.watchList==NULL)
        self.watchList=[[NSArray alloc] init];
    self.managers=[self.dataManager getGroupManagers:self.groupId accountId:self.user.uid deviceUid:self.selectWatch.deviceUid];
    if(self.managers==NULL)
        self.managers=[[NSArray alloc] init];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.managers.count+self.watchList.count+1;//家庭圈  还有手表
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *cellIdentifier = @"ChatListTableViewCell";
    NSInteger row=[indexPath row];
    if(!self.isRegis)
    {
        [tableView registerNib:[UINib nibWithNibName:@"ChatListTableViewCell" bundle:nil] forCellReuseIdentifier: cellIdentifier];
        self.isRegis=YES;
    }
   ChatListTableViewCell *cell = (ChatListTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    int unread=0;
    if(row==0)//家庭圈
    {
        cell.headImg.image=[UIImage imageNamed:@"group"];
        cell.titleLable.text=@"家庭圈";
        unread=[self.dataManager getGroupChatNums:self.groupId accountId:self.user.uid];
        if(unread>0)
        {
            cell.unreadImg.hidden=NO;
            cell.unreadLable.hidden=NO;
            cell.unreadLable.text=[NSString stringWithFormat:@"%d",unread];
        }
        else
        {
            cell.unreadImg.hidden=YES;
            cell.unreadLable.hidden=YES;
        }
        NSString *latestTime=[self.dataManager getLatestGroupChatTime:self.groupId accountId:self.user.uid];
        if(latestTime!=NULL)
        {
            cell.timeLable.hidden=NO;
            cell.timeLable.text=[Tooler getDateTime:latestTime];
        }
        else
        {
            cell.timeLable.hidden=YES;
        }
        return cell;
    }
    if(row<=[self.watchList count])//手表
    {
        Watch *watch=[self.watchList objectAtIndex:row-1];
        if(watch==NULL)
            return cell;
        if(watch.pic_url!=NULL&&![watch.pic_url isEqualToString:@"(null)"]&&![watch.pic_url isEqualToString:@""])
        {
            //cell.headImg.image=[UIImage imageNamed:[self.documentDirectory stringByAppendingString:watch.pic_url]];
            cell.headImg.image=[UIImage imageWithContentsOfFile:[self.documentDirectory stringByAppendingString:watch.pic_url]];
        }
        else
        {
            if(watch.gender==1)//nv
            {
                cell.headImg.image=[UIImage imageNamed:@"avater_girl.png"];
            }
            else
            {
                cell.headImg.image=[UIImage imageNamed:@"avater_boy.png"];
            }
        }
        
        if(watch.nickname!=NULL&&![watch.nickname isEqualToString:@"(null)"])
        {
            cell.titleLable.text=watch.nickname;
        }
        else
        {
            cell.titleLable.text=@"宝宝";
        }
        
        unread=[self.dataManager getSingleChatNums:watch.deviceUid myId:self.user.uid];
        if(unread>0)
        {
            cell.unreadImg.hidden=NO;
            cell.unreadLable.hidden=NO;
            cell.unreadLable.text=[NSString stringWithFormat:@"%d",unread];
        }
        else
        {
            cell.unreadImg.hidden=YES;
            cell.unreadLable.hidden=YES;
        }
        NSString *latestTime=[self.dataManager getLatestSigleChatTime:watch.deviceUid accountId:self.user.uid];
        if(latestTime!=NULL)
        {
            cell.timeLable.hidden=NO;
            cell.timeLable.text=[Tooler getDateTime:latestTime];
        }
        else
        {
            cell.timeLable.hidden=YES;
        }
        return cell;
    }
    
    Manager *manager=[self.managers objectAtIndex:(row-[self.watchList count]-1)];
    if(manager==NULL)
    {
        return cell;
    }
    if(manager.pic_url!=NULL&&![manager.pic_url isEqualToString:@"(null)"])
    {
       cell.headImg.image=[UIImage imageNamed:[self.documentDirectory stringByAppendingString:manager.pic_url]];
    }
    else
    {
        cell.headImg.image=[UIImage imageNamed:@"avater_other.png"];
    }
    if(manager.nickName==NULL||[manager.nickName isEqualToString:@"(null)"])
    {
        if(manager.type==ADMIN)
        {
           cell.titleLable.text=@"主管理员";
        }
        else
        {
           cell.titleLable.text=@"副管理员";
        }

    }
    else
    {
        cell.titleLable.text=manager.nickName;
    }
    unread=[self.dataManager getSingleChatNums:manager.user_id myId:self.user.uid];
    if(unread>0)
    {
        cell.unreadImg.hidden=NO;
        cell.unreadLable.hidden=NO;
        cell.unreadLable.text=[NSString stringWithFormat:@"%d",unread];
    }
    else
    {
        cell.unreadImg.hidden=YES;
        cell.unreadLable.hidden=YES;
    }
    NSString *latestTime=[self.dataManager getLatestSigleChatTime:manager.user_id accountId:self.user.uid];
    if(latestTime!=NULL)
    {
        cell.timeLable.hidden=NO;
        cell.timeLable.text=[Tooler getDateTime:latestTime];
    }
    else
    {
        cell.timeLable.hidden=YES;
    }
    return cell;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80.0f*self.rate;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row=[indexPath row];
    ChatViewController *chatView=[[ChatViewController alloc] init];
    if(chatView==NULL)
    {
        NSLog(@"%@,didSelectRowAtIndexPath,chatView is null.",chat_tag);
        return;
    }
    if(row==0)
    {
        chatView.type=1;
        if(self.selectWatch!=NULL)
            chatView.deviceUid=self.selectWatch.deviceUid;
        chatView.groupId=self.groupId;
    }
    else if(row<=[self.watchList count])
    {
        Watch *watch=[self.watchList objectAtIndex:row-1];
        chatView.type=2;
        if(watch!=NULL)
            chatView.deviceUid=watch.deviceUid;
    }
    else
    {
        chatView.type=3;
        if(self.selectWatch!=NULL)
            chatView.deviceUid=self.selectWatch.deviceUid;
        Manager *manager=[self.managers objectAtIndex:(row-[self.watchList count]-1)];
        if(manager!=NULL)
            chatView.managerId=manager.user_id;
    }
    [self.navigationController pushViewController:chatView animated:YES];    
}



-(void)syncChatData
{
    NSLog(@"%@,syncChatData entered",chatList_tag);
    NSString *seqIdBegin=[self.dataManager getseqId:self.groupId];
    [self.syncManager getGroupChatRecords:self.groupId seqIdBegin:seqIdBegin limit:100 deviceUid:self.selectWatch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                    if(result==SUCESS)
                    {
                        NSLog(@"%@,getGroupChatRecords success.",chatList_tag);
                    }
                    else
                    {
                        NSLog(@"%@,getGroupChatRecordes fail.",chatList_tag);
                    }
                }];

    if(self.managers!=NULL)
    {
        for(int i=0;i<[self.managers count];i++)
        {
            Manager *manager=[self.managers objectAtIndex:i];
            if(manager==NULL)
                continue;
            NSString *targetUid=manager.user_id;
            if(targetUid==NULL)
                continue;
            NSString *seqIdBegin=[self.dataManager getseqIdSingle:targetUid];
            [self.syncManager getSingleChatRecords:targetUid seqIdBegin:seqIdBegin limit:100 deviceUid:self.selectWatch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                if(result==SUCESS)
                {
                    NSLog(@"%@,getSingleChatRecords success,targetUid is %@.",chatList_tag,targetUid);
                }
                else
                {
                   NSLog(@"%@,getSingleChatRecords fail,targetUid is %@.",chatList_tag,targetUid);
                }
                
            }];
        }
    }
    __block int syncNums=0;
    if(self.watchList!=NULL)
    {
        if(syncNums==[self.watchList count])
        {
            self.mydelegate.chat_sync=YES;
            self.isSyncFinish=YES;
        }
        for(int i=0;i<[self.watchList count];i++)
        {
            Watch *watch=[self.watchList objectAtIndex:i];
            if(watch==NULL)
            {
                syncNums++;
                if(syncNums==[self.watchList count])
                {
                    self.mydelegate.chat_sync=YES;
                    self.isSyncFinish=YES;
                }
                continue;
            }
            NSString *targetUid=watch.deviceUid;
            if(targetUid==NULL)
            {
                syncNums++;
                if(syncNums==[self.watchList count])
                {
                    self.mydelegate.chat_sync=YES;
                    self.isSyncFinish=YES;
                }
                continue;
            }
            NSString *seqIdBegin=[self.dataManager getseqIdSingle:targetUid];
            [self.syncManager getSingleChatRecords:targetUid seqIdBegin:seqIdBegin limit:100 deviceUid:self.selectWatch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                if(result==SUCESS)
                {
                    NSLog(@"%@,getSingleChatRecords success,targetUid is %@.",chatList_tag,targetUid);
                }
                else
                {
                    NSLog(@"%@,getSingleChatRecords fail,targetUid is %@.",chatList_tag,targetUid);
                }
                syncNums++;
                if(syncNums==[self.watchList count])
                {
                    self.mydelegate.chat_sync=YES;
                    self.isSyncFinish=YES;
                }
                
            }];
            
        }
    }
    else
    {
        self.mydelegate.chat_sync=YES;
        self.isSyncFinish=YES;
    }

}
-(void)registerObservers
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:SYNCCHATDATAFINISHED object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:CHANGEWATCH object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:USERINFOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:WATCHPHOTOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:MANAGERPHOTOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:UNBINDDEVICE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:BINDRELATIONCHANGE object:nil];
}
-(void)removeObservers
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SYNCCHATDATAFINISHED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CHANGEWATCH object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:USERINFOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:WATCHPHOTOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MANAGERPHOTOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UNBINDDEVICE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BINDRELATIONCHANGE object:nil];
}

- (void)receiveNotification:(NSNotification *)sender {
    if([sender.name isEqualToString:SYNCCHATDATAFINISHED])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self loadData];
            [self.tableView reloadData];
            //获取所有未读消息数
            [self updateUnreadNums];
        });
        
    }
    else if([sender.name isEqualToString:CHANGEWATCH])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self loadData];
            [self.tableView reloadData];
            [self syncChatData];
            [self updateUnreadNums];

        });                
    }
    else if([sender.name isEqualToString:USERINFOUPDATE])
    {
        [self loadData];
        [self.tableView reloadData];
    }
    else if([sender.name isEqualToString:WATCHPHOTOUPDATE])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self loadData];
            [self.tableView reloadData];
        });

    }
    else if([sender.name isEqualToString:MANAGERPHOTOUPDATE])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self loadData];
            [self.tableView reloadData];
        });

    }
    else if([sender.name isEqualToString:UNBINDDEVICE])
    {
        [self loadData];
        [self.tableView reloadData];
        [self updateUnreadNums];
        

    }
    else if([sender.name isEqualToString:BINDRELATIONCHANGE])
    {
        [self loadData];
        [self.tableView reloadData];
        [self updateUnreadNums];
    }

}
-(void)updateUnreadNums
{
    if(self.dataManager==NULL)
        return;
    int unRead=[self.dataManager getUnReadNums:self.selectWatch.deviceUid groupId:self.groupId accountId:self.user.uid];
    if(unRead>0)
    {
        self.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",unRead];
    }
    else
    {
        self.tabBarItem.badgeValue=nil;
    }
}
@end
